<template>
  <div class="goods-comment">
    <!-- 评价头部 -->
    <div class="head" v-if="commentInfo">
      <div class="data">
        <p>
          <!-- {{commentInfo}} -->
          <span>{{ commentInfo.salesCount }}</span
          ><span>人购买</span>
        </p>
        <p>
          <span>{{ commentInfo.praisePercent }}</span
          ><span>好评率</span>
        </p>
      </div>
      <div class="tags">
        <div class="dt">大家都在说：</div>
        <div class="dd">
          <a
            v-for="(item,i) in commentInfo.tags"
            :key="item.title"
            href="javascript:;"
            :class="{active:currTagIndex===i}"
            @click="changeTag(i)"
          >
            {{item.title}}（{{item.tagCount}}）
          </a>
        </div>
      </div>
    </div>
    <!-- 排序 -->
    <div class="sort" v-if="commentInfo">
      <span>排序：</span>
      <a
          @click="changeSort(null)"
          href="javascript:;"
          :class="{active:reqParams.sortField===null}"
        >默认</a>
        <a
          @click="changeSort('praiseCount')"
          href="javascript:;"
          :class="{active:reqParams.sortField==='praiseCount'}"
        >最热</a>
        <a
          @click="changeSort('createTime')"
          href="javascript:;"
          :class="{active:reqParams.sortField==='createTime'}"
        >最新</a>
    </div>
    <!-- 评价列表 -->
    <div class="list" v-if="commentList">
      <div class="item" v-for="item in commentList" :key="item.id">
        <!-- 用户信息 -->
        <div class="user">
          <img :src="item.member.avatar" alt="">
          <span>{{formatNickname(item.member.nickname)}}</span>
        </div>

        <div class="body">
          <!-- 打星评价 -->
          <div class="score">
            <!-- 实心的打星评价的星星 -->
             <!-- key的作用是区分唯一标识 是实心和空心不能一样,可以是1,2也可以是s和k -->
            <i v-for="i in item.score" :key="i+'s'" class="iconfont icon-wjx01"></i>
            <!-- 空心(不显示)的打星评价的星星 -->
            <i v-for="i in 5-item.score" :key="i+'k'" class="iconfont icon-wjx02"></i>
            <span class="attr">{{formatSpecs(item.orderInfo.specs)}}</span>
          </div>
          <div class="text">{{item.content}}</div>
          
          <!-- 评论图片预览组件 -->
          <GoodsCommentImage v-if="item.pictures.length" :pictures="item.pictures" />

          <div class="time">
            <!-- 评论时间 -->
            <span>{{item.createTime}}</span>
            <!-- 点赞数量 -->
            <span class="zan"><i class="iconfont icon-dianzan"></i> {{item.praiseCount}}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页组件 -->
    <XtxPagination v-if="total" @current-change="changePageFn" :total="total" :page-size="reqParams.pageSize" :current-page="reqParams.page"/>

  </div>
</template>
<script>
import { findCommentInfoByGoods,findCommentGoodsList } from "@/api/product";
import { ref,reactive,watch } from "vue";
import { inject } from "vue";
import GoodsCommentImage from './goods-comment-image'

// 方法1  不建议 因为props.goods为undefined是会出现props.goods.id错误
// const getCommentInfo = (props) => {
//   const commentInfo = ref(null)
//   // console.log(props.goods);
//   findCommentInfoByGoods(props.goods.id).then(data => {
//     // type 的目的是将来点击可以区分点的是不是标签
//     data.result.tags.unshift({ type: 'img', title: '有图', tagCount: data.result.hasPictureCount })
//     data.result.tags.unshift({ type: 'all', title: '全部评价', tagCount: data.result.evaluateCount })
//     commentInfo.value = data.result
//   })
//   return commentInfo
// }
export default {
  name: "GoodsComment",
  components: { GoodsCommentImage },
  // props: {
  //   // 方法1
  //   goods: {
  //     type: Object,
  //     default: () => {}
  //   }
  // },
  setup(props) {
    // 获取评价信息
    // 方法1
    // const commentInfo = getCommentInfo(props)
    // 方法2
    const commentInfo = ref(null);
    const goods = inject("goods");
    // console.log(goods.value.id);
    findCommentInfoByGoods(goods.value.id).then((data) => {
      // console.log(data);
      // 在设置数据之前,tags数组前追加 有图tag  全部评价tag
      data.result.tags.unshift({
        type: "img",
        title: "有图",
        tagCount: data.result.hasPictureCount,
      });
      data.result.tags.unshift({
        type: "all",
        title: "全部评价",
        tagCount: data.result.evaluateCount,
      });
      // 设置数据
      commentInfo.value = data.result;
      // console.log(commentInfo);
    });


     // 记录当前激活的索引
    //  默认为全部评价
    const currTagIndex = ref(0)
    const changeTag = (i) => {
      currTagIndex.value = i
      // 点击tag的时候修改筛选条件
      // 设置有图和标签条件
      const tag = commentInfo.value.tags[i]
      // console.log(tag);
      // 情况1:全部评价
      // 情况2:有图
      // 情况3:正常tag
      if (tag.type === 'all') {
        // reqParams.hasPicture = false
        reqParams.hasPicture = null
        reqParams.tag = null
      } else if (tag.type === 'img') {
        reqParams.hasPicture = true
        reqParams.tag = null
      } else {
        // reqParams.hasPicture = false
        reqParams.hasPicture = null
        reqParams.tag = tag.title
      }
      // 页码重置为1
      reqParams.page = 1
    }


    // 点击排序,改变排序
      const changeSort = (type) => {
        reqParams.sortField = type
      // 页码重置为1
         reqParams.page = 1
      }


    // 准备筛选条件数据
    const reqParams = reactive({
      page: 1,
      pageSize: 10,
      // 如果值为false,还会传数据,为null(空)就不会传
      hasPicture: null,
      tag: null,
      // 排序方式   praiseCount  热度  createTime 最新
      sortField: null
    })
    // console.log(reqParams);

    // 初始化需要发请求,筛选条件发生改变发请求，获取列表数据。
    const commentList = ref([])
    // 记录总条数
    const total=ref(0)
    watch(reqParams,()=>{
      // console.log('发请求');
      // console.log(goods.value.id);
      findCommentGoodsList(goods.value.id,reqParams).then(data=>{
        // console.log(data);
        commentList.value = data.result.items
        // console.log(data.result.items);
        // console.log(commentList);
        
        total.value=data.result.counts
      })
    },{immediate:true})


     // 定义转换数据的函数（对应vue2.0的过滤器）
    //  选中商品的规格(属性)的变化
    const formatSpecs = (specs) => {
      return specs.reduce((p, c) => `${p} ${c.name}：${c.nameValue}`, '').trim()
    }
    // 用户名的变化
    const formatNickname = (nickname) => {
      // .substr(0, 1) 获取字符串序号0开始的一个字符
      // .substr(-1) 获取最后一个字符
      return nickname.substr(0, 1) + '****' + nickname.substr(-1)
    }

    // 实现分页切换
    const changePageFn = (newPage) => {
      reqParams.page = newPage
    }

    return { commentInfo, currTagIndex,changeSort, changeTag ,reqParams,commentList, formatSpecs, formatNickname,total,changePageFn }
  },
};
</script>
<style scoped lang="less">
.goods-comment {
  .head {
    display: flex;
    padding: 30px 0;
    .data {
      width: 340px;
      display: flex;
      padding: 20px;
      p {
        flex: 1;
        text-align: center;
        span {
          display: block;
          &:first-child {
            font-size: 32px;
            color: @priceColor;
          }
          &:last-child {
            color: #999;
          }
        }
      }
    }
    .tags {
      flex: 1;
      display: flex;
      border-left: 1px solid #f5f5f5;
      .dt {
        font-weight: bold;
        width: 100px;
        text-align: right;
        line-height: 42px;
      }
      .dd {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
        > a {
          width: 132px;
          height: 42px;
          margin-left: 20px;
          margin-bottom: 20px;
          border-radius: 4px;
          border: 1px solid #e4e4e4;
          background: #f5f5f5;
          color: #999;
          text-align: center;
          line-height: 40px;
          &:hover {
            border-color: @xtxColor;
            background: lighten(@xtxColor, 50%);
            color: @xtxColor;
          }
          &.active {
            border-color: @xtxColor;
            background: @xtxColor;
            color: #fff;
          }
        }
      }
    }
  }
  .sort {
    height: 60px;
    line-height: 60px;
    border-top: 1px solid #f5f5f5;
    border-bottom: 1px solid #f5f5f5;
    margin: 0 20px;
    color: #666;
    > span {
      margin-left: 20px;
    }
    > a {
      margin-left: 30px;
      &.active,
      &:hover {
        color: @xtxColor;
      }
    }
  }
}
 .list {
    padding: 0 20px;
    .item {
      display: flex;
      padding: 25px 10px;
      border-bottom: 1px solid #f5f5f5;
      .user {
        width: 160px;
        img {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          overflow: hidden;
        }
        span {
          padding-left: 10px;
          color: #666;
        }
      }
      .body {
        flex: 1;
        .score {
          line-height: 40px;
          .iconfont {
            color: #ff9240;
            padding-right: 3px;
          }
          .attr {
            padding-left: 10px;
            color: #666;
          }
        }
      }
      .text {
        color: #666;
        line-height: 24px;
      }
      .time {
        color: #999;
        display: flex;
        justify-content: space-between;
        margin-top: 5px;
      }
    }
  }
</style>